﻿using AutoMapper;
using IntelligentAgriculture.Contracts.Dto.Output;
using IntelligentAgriculture.Contracts.Interface;
using IntelligentAgriculture.Domain;
using IntelligentAgriculture.Domain.Entity;
using IntelligentAgriculture.Domain.Impl;
using IntelligentAgriculture.Domain.Interface;
using IntelligentAgriculture.Domain.Interface.IColumnManagement;
using IntelligentAgriculture.Domain.Interface.Iridgepletype;
using IntelligentAgriculture.Domain.Interface.SheepFileModelInterface;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace IntelligentAgriculture.Services
{
    public class ParturitionService:IParturitionService
    {
        private readonly IParturitionRepository _parturitionRepository;
        private readonly IPregnancyRepository _pregnancyRepository;
        private readonly IridegRepository _iridegRepository;
        private readonly IColumnManRepository _columnManRepository;
        //历史
        private readonly IHistoryRecordRepository _historyRecordRepository;
        //档案
        private readonly ISheepFileModelRepository _sheepFileModelRepository;
        //转舍
        private readonly ISheepRescissionRepository _sheepRescissionRepository;
        private readonly AgricultureDbContext _context;
        private readonly IMapper _mapper;
        public ParturitionService(IParturitionRepository parturitionRepository, IPregnancyRepository pregnancyRepository, IridegRepository iridegRepository, IColumnManRepository columnManRepository, IHistoryRecordRepository historyRecordRepository, ISheepFileModelRepository sheepFileModelRepository, ISheepRescissionRepository sheepRescissionRepository, AgricultureDbContext context, IMapper mapper)
        {
            _parturitionRepository = parturitionRepository;
            _pregnancyRepository = pregnancyRepository;
            _iridegRepository = iridegRepository;
            _columnManRepository = columnManRepository;
            _historyRecordRepository = historyRecordRepository;
            _sheepFileModelRepository = sheepFileModelRepository;
            _sheepRescissionRepository = sheepRescissionRepository;
            _context = context;
            _mapper = mapper;
        }
        /// <summary>
        /// 种母分娩列表
        /// </summary>
        /// <param name="startChildbirthDate"></param>
        /// <param name="endChildbirthDate"></param>
        /// <param name="eartag"></param>
        /// <param name="buildingId"></param>
        /// <param name="toBuildingId"></param>
        /// <param name="broodNumber"></param>
        /// <param name="userId"></param>
        /// <param name=""></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<PageOutput<ParturitionOutput>> GetParturition(string? startChildbirthDate,string? endChildbirthDate,string eartag,int? buildingId, int? toBuildingId, string? broodNumber,int? userId,int pageIndex, int pageSize)
        {
            var query = await _parturitionRepository.GetChildbirth();
            //栋舍
            var rigin = _iridegRepository.Showinfo();
            //栏位
            var columns = _columnManRepository.GetShow();
            var entity = (from parturition in query
                         join ridgepole in rigin on parturition.CurrentBuilding equals ridgepole.RidgepoleId
                         join column in columns on parturition.CurrentField equals column.ColumnManagementId
                         select new ParturitionOutput
                         {
                             ChildbirthId = parturition.ChildbirthId,
                             EarTag = parturition.EarTag,
                             ChildbirthDate = parturition.ChildbirthDate,
                             GestationDays = parturition.GestationDays,
                             DifficultyDelivery = parturition.DifficultyDelivery,
                             MotherHood = parturition.MotherHood,
                             Lactation = parturition.Lactation,
                             DieLambAvgWeight = parturition.DieLambAvgWeight,
                             AuditDate = parturition.AuditDate,
                             AuditName = parturition.AuditName,
                             BroodNumber = parturition.BroodNumber,
                             BroodWeight = parturition.BroodWeight,
                             CreateName = parturition.CreateName,
                             CreateTime = parturition.CreateTime,
                             DieLambNum = parturition.DieLambNum,
                             DieLambWeight = parturition.DieLambWeight,
                             DocumentNumber = parturition.DocumentNumber,
                             FatSheep = parturition.FatSheep,
                             FreaksNumber = parturition.FreaksNumber,
                             HealthyNumber = parturition.HealthyNumber,
                             LambNumber = parturition.LambNumber,
                             LitterWeight = parturition.LitterWeight,
                             LiveLambAvgWeight  = parturition.LiveLambAvgWeight,
                             LiveLambNum = parturition.LiveLambNum,
                             LiveLambWeight = parturition.LiveLambWeight,
                             MalformationNumber = parturition.MalformationNumber,
                             LiveNumber = parturition.LiveNumber,
                             MummyNumber = parturition.MummyNumber,
                             Mastitis = parturition.Mastitis,
                             StillbirthNumber = parturition.StillbirthNumber,
                             Sex = parturition.Sex,
                             UpdateName = parturition.UpdateName,
                             UpdateTime = parturition.UpdateTime,
                             UserId = parturition.UserId,
                             //当前栋舍
                             CurrentBuilding =ridgepole.RidgepoleId,
                             BuildingName = rigin.FirstOrDefault(c => c.RidgepoleId == parturition.CurrentBuilding).RidgepoleName,
                             //当前栏位
                             CurrentField = column.ColumnManagementId,
                             ColumnName = columns.FirstOrDefault(c => c.ColumnManagementId == parturition.CurrentField).ColumnName,
                             //转入栋舍
                             ToBuildingManageId = ridgepole.RidgepoleId,
                             ToBuildingName = rigin.FirstOrDefault(c => c.RidgepoleId == parturition.ToBuildingManageId).RidgepoleName,
                             //转入栏位
                             ToColumMangementId = column.ColumnManagementId,
                             ToColumnName = columns.FirstOrDefault(c => c.ColumnManagementId == parturition.ToColumMangementId).ColumnName,

                         });
            if(!string.IsNullOrEmpty(startChildbirthDate))
            {
                entity =entity.Where(c=>c.ChildbirthDate>=DateTime.Parse(startChildbirthDate));
            }
            if(!string.IsNullOrEmpty(endChildbirthDate))
            {
                entity =entity.Where(c=>c.ChildbirthDate<=DateTime.Parse(endChildbirthDate));
            }
            if(!string.IsNullOrEmpty(eartag))
            {
                entity =entity.Where(c=>c.EarTag==eartag);
            }
            if(buildingId>0)
            {
                entity =entity.Where(c=>c.CurrentBuilding==buildingId);
            }
            if(toBuildingId>0)
            {
                entity =entity.Where(c=>c.ToBuildingManageId==toBuildingId);
            }
            if(!string.IsNullOrEmpty(broodNumber))
            {
                entity =entity.Where(c=>c.BroodNumber==broodNumber);
            }
            if(userId>0)
            {
                entity =entity.Where(c=>c.UserId==userId);
            }
            var result = new PageOutput<ParturitionOutput>
            {
                TotalCount = entity.Count(),
                PageSize = pageSize,
            };
            entity = entity.OrderByDescending(c => c.CreateTime).Skip(pageSize * (pageIndex - 1)).Take(pageSize);
            result.Data = _mapper.Map<List<ParturitionOutput>>(entity);
            return result;
        }
        /// <summary>
        /// 种母分娩添加
        /// </summary>
        /// <param name="sheeppregnancy"></param>
        /// <returns></returns>
        public async Task<int> AddChildbirth(List<Childbirth> childbirth)
        {
            try
            {
                childbirth.ForEach(c =>
                {
                    c.CreateTime = DateTime.Now;
                    c.CreateName = "赵思彤";
                    c.UpdateTime = DateTime.Now;
                    c.Isdel = false;
                    c.DocumentNumber = YitIdHelper.NextId().ToString();
                });
                await _parturitionRepository.AddChildbirth(childbirth);
                //获取耳号
                var des = childbirth.Select(c => c.EarTag).ToList();
                //获取妊检信息
                var PList = await _pregnancyRepository.GetSheeppregnancy();
                //添加分娩数据 删除妊检
                var pregnancy = PList.Where(c => des.Contains(c.EarTag)).ToList();
                pregnancy.ForEach(c =>
                {
                    c.EarTag = childbirth.FirstOrDefault(s => s.EarTag == c.EarTag).EarTag;
                    c.IsDel = true;
                });
                await _pregnancyRepository.UpdSheeppregnancys(pregnancy);
                //获取种母历史记录
                var HList = await _historyRecordRepository.GetHistoryRecordsAsync();
                var history = HList.Where(c => des.Contains(c.EarTag)).ToList();
                //修改历史记录
                history.ForEach(c =>
                {
                    c.EarTag = childbirth.FirstOrDefault(s => s.EarTag == c.EarTag).EarTag;
                    c.DeliveryDate = childbirth.FirstOrDefault(s => s.EarTag == c.EarTag).ChildbirthDate;
                    c.HealthyNumber = childbirth.FirstOrDefault(s => s.EarTag == c.EarTag).HealthyNumber;
                    c.LambNumber = childbirth.FirstOrDefault(s => s.EarTag == c.EarTag).LambNumber;
                    c.MalformationNumber = childbirth.FirstOrDefault(s => s.EarTag == c.EarTag).MalformationNumber;
                    c.StillbirthNumber = childbirth.FirstOrDefault(s => s.EarTag == c.EarTag).StillbirthNumber;
                    c.MummyNumber = childbirth.FirstOrDefault(s => s.EarTag == c.EarTag).MummyNumber;
                    c.FreaksNumber = childbirth.FirstOrDefault(s => s.EarTag == c.EarTag).FreaksNumber;
                });
                await _historyRecordRepository.ListUpdateHisRecordAsync(history);
                //获取档案表
                var SList = await _sheepFileModelRepository.GetSheepfilemodels();
                var sheepfile =SList.Where(c=>des.Contains(c.EarTag)).ToList();
                //修改档案表数据
                sheepfile.ForEach(c =>
                {
                    c.EarTag = childbirth.FirstOrDefault(s => s.EarTag == c.EarTag).EarTag;
                    c.BuildingId = childbirth.FirstOrDefault(s => s.EarTag == c.EarTag).ToBuildingManageId;
                    c.ColumnId = childbirth.FirstOrDefault(s => c.EarTag == c.EarTag).ToColumMangementId;
                    c.ReproductionState = 8;
                });
                await _sheepFileModelRepository.UpdateListSheepFileModel(sheepfile);
                //添加羊只转舍
                var sheepRescission = childbirth.Select(item => new Sheeprescission
                {
                        SheepRescissionDate = DateTime.Now,
                        EarTag = item.EarTag,
                        RoundType = 3,
                        OutBuildingManageId = item.CurrentBuilding,
                        OutColumMangementId =item.CurrentField,
                        ToBuildingManageId = item.ToBuildingManageId,
                        ToColumMangementId = item.ToColumMangementId,
                        SheepType =2,
                        Variety = sheepfile.FirstOrDefault(c=>c.EarTag==item.EarTag)?.Variety,
                        SheepRescissionSex = sheepfile.FirstOrDefault(c => c.EarTag == item.EarTag)?.SheepSex,
                        CreateName =item.CreateName,
                        CreateTime =DateTime.Now,
                        UpdateName =item.UpdateName,
                        UpdateTime =DateTime.Now,
                        DocumentNumber =YitIdHelper.NextId().ToString(),
                        Isdel =item.Isdel

                }).ToList();
                return await _sheepRescissionRepository.AddSheepRescission(sheepRescission);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 种母分娩删除
        /// </summary>
        /// <param name="pregnancyId"></param>
        /// <returns></returns>
        public async Task<int> DeleParturition(string? eartag)
        {
            try
            {
                var result = await _parturitionRepository.DeleParturition(eartag);
                return result;
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
